package com.kaigejava.guanchazhemoshi.observermodel;

import com.kaigejava.guanchazhemoshi.observermodel.interfaceObj.Observer;
import com.kaigejava.guanchazhemoshi.observermodel.interfaceObj.Subject;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kaigejava on 2019/8/12.
 * 天气对象，实现了Subject接口
 */
@Data
public class WeatherDataSt implements Subject{
    public  WeatherDataSt(){}
    /**
     * 温度
     */
    private float temperatrue;
    /**
     * 气压
     */
    private float pressure;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * observer集合。用于存放observer对象的的
     */
    private List<Observer> observerList = new ArrayList<>();
    public void dataChange()
    {
        notifyObservers();
    }
    /**
     * 模拟气象变化
     * @param temperatrue
     * @param pressure
     * @param humidity
     */
    public void setData(float temperatrue,float pressure,float humidity)
    {
        this.temperatrue=temperatrue;
        this.pressure=pressure;
        this.humidity=humidity;
        dataChange();
    }

    /**
     * 向subject注册
     * @param observer
     */
    @Override
    public void registerObserver(Observer observer) {
        observerList.add(observer);
    }

    /**
     * 从subject中移除observer对象
     * @param observer
     */
    @Override
    public void removeObserver(Observer observer) {
        if(observerList.contains(observer)){
            observerList.remove(observer);
        }
    }

    /**
     * 天气发生变化后，通知每个observer
     */
    @Override
    public void notifyObservers() {
        for(Observer observer:observerList){
            observer.updte(this.getTemperatrue(), this.getPressure(),this.getHumidity());
        }
    }
}
